#!/usr/bin/env bash

# save logs if script errors and exits early
chain_number=1
function on_exit {
  save_logs $chain_number
}
trap on_exit EXIT

# set this directory as working directory
cd "$(dirname "$0")"
# import test helpers
source ./test_helpers

# build docker images, reset CL db
initial_setup
mkdir -p logs

# run the first chain, where the ethlog contract is deployed
printf "\nSTARTING CHAIN 1\n"
# make sure chainlink has actually started receiving blocks from geth
search_chainlink_logs 'Received new head'
# broadcast contract creation transaction
create_contract
# wait for chainlink to get notified about transaction
search_chainlink_logs 'New run triggered by ethlog'
search_chainlink_logs 'Pausing run pending confirmations'
# stop mining before sufficient confirmations can be reached
docker-compose stop
# assert that nothing has been uncled yet
assert_not_in_chainlink_logs 'presumably has been uncled'
# tear down
save_logs 1
docker-compose down

# create 2nd chain that is longer than first chain. Job should be uncled, not run
printf "\nSTARTING CHAIN 2\n"
chain_number=2
start_network
# 2nd chain should be younger than first, and so chainlink won't immediately save new heads
search_chainlink_logs 'Cannot save new head confirmation'
# when 2nd chain gets longer, chainlink resumes saving heads
search_chainlink_logs 'New connection resuming run'
# will wait for head # to be 10 more than block # with contract creation
search_chainlink_logs 'Cannot save new head confirmation'
# should eventually abort running running job
search_chainlink_logs 'presumably has been uncled'
# assert job was never run
docker-compose stop
assert_not_in_chainlink_logs 'All tasks complete for run'
# tear down
save_logs 2
docker-compose down

echo "test passed!"
